package com.wsoft.bpm.component.sign;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.wsoft.bpm.entity.ActAddSignEntity;
import com.wsoft.bpm.mapper.ActAddSignMapper;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineLifecycleListener;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * 工作流启动后自动添加加签数据
 *
 * @author zhonglj
 * @return
 * @date 2024/12/3 11:15
 **/
@Slf4j
public class AddSignProcessEngineLifecycleListener implements ProcessEngineLifecycleListener {
    @Override
    public void onProcessEngineBuilt(ProcessEngine processEngine) {
        ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
        SqlSessionFactory sqlSessionFactory = processEngineConfiguration.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ActAddSignMapper addSignMapper = sqlSession.getMapper(ActAddSignMapper.class);
        List<ActAddSignEntity> addSignList = addSignMapper.activityFind();
        for (ActAddSignEntity addSign : addSignList) {
            String processDefinitionId = addSign.getProcessDefinitionId();
            String processInstanceId = addSign.getProcessInstanceId();
            String propertiesText = addSign.getPropertiesText();
            String activityId = addSign.getActivityId();
            TmpActivityModel tmpActivityModel = JSON.parseObject(propertiesText, TmpActivityModel.class);
            DynamicUserTaskComponent dynamicUserTaskComponent = new DynamicUserTaskComponent();

            if (CollUtil.isNotEmpty(tmpActivityModel.getAssignList())) {
                // 多实例并行
                dynamicUserTaskComponent.addSignUserTask(processDefinitionId, processInstanceId, processEngine, tmpActivityModel.getAssignList(), tmpActivityModel.getFirstId(), tmpActivityModel.getLastId(), false, false, null, activityId);

            } else if (CollUtil.isNotEmpty(tmpActivityModel.getActivityList())) {
                dynamicUserTaskComponent.addDynamicUserTask(processDefinitionId, processInstanceId, processEngine, tmpActivityModel.getActivityList(), tmpActivityModel.getFirstId(), tmpActivityModel.getLastId(), false, false, null, activityId);
            }
        }
    }

    @Override
    public void onProcessEngineClosed(ProcessEngine processEngine) {

    }
}
